package com.lzh.persevere.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.lzh.persevere.common.R;
import com.lzh.persevere.common.ResultUtil;
import com.lzh.persevere.exception.LzhException;
import com.lzh.persevere.model.entity.FriendCycle;
import com.lzh.persevere.model.qo.friendCycle.FindFriendCyclePageQO;
import com.lzh.persevere.model.ro.friendCycle.AddFriendCycleRO;
import com.lzh.persevere.model.vo.friendCycle.FriendCycleVO;
import com.lzh.persevere.service.FriendCycleService;
import com.lzh.persevere.service.impl.RedisCacheService;
import com.lzh.persevere.utils.IpUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 朋友圈controller
 *
 * @author luzhiheng
 * @since 2025-07-07
 */
@RestController
@RequestMapping("/friendCycle")
public class FriendCycleController {

    @Resource
    private FriendCycleService friendCycleService;

    @Resource
    private RedisCacheService redisCacheService;

    @ApiOperation(value = "分页查询朋友圈列表")
    @PostMapping("/findFriendCyclePageList")
    public R<Map<String, Object>> findFriendCyclePageList(@Valid @RequestBody FindFriendCyclePageQO qo) {
        return ResultUtil.success(friendCycleService.pageList(qo));
    }

    @ApiOperation(value = "添加朋友圈")
    @PostMapping("/addFriendCycle")
    public R<FriendCycleVO> addFriendCycle(@Valid @RequestBody AddFriendCycleRO ro) {
        if (StrUtil.isEmpty(ro.getContent()) && CollectionUtil.isEmpty(ro.getImgIds())) {
            throw new LzhException(600, "请输入内容或上传图片");
        }


        Map<String, String> allUserIdAvatarMap = redisCacheService.getAllUserIdAvatarMap();
        Map<String, String> allUserIdNickNameMap = redisCacheService.getAllUserIdNickNameMap();

        FriendCycle friendCycle = new FriendCycle()
                .setTag(String.join(",", ro.getTagList()))
                .setIp(IpUtil.getIpAddress())
                .setFileIds(ro.getImgIds().stream().map(Object::toString).collect(Collectors.joining(",")))
                .setContent(ro.getContent());
        friendCycleService.save(friendCycle);
        FriendCycleVO friendCycleVO = BeanUtil.copyProperties(friendCycle, FriendCycleVO.class);
        friendCycleVO.setAvatar(allUserIdAvatarMap.get(friendCycle.getCreateUserId()));
        friendCycleVO.setCreateNickName(allUserIdNickNameMap.get(friendCycle.getCreateUserId()));

        return ResultUtil.success(friendCycleVO);
    }
}
